<template>
    <base-breadcrumb>
        <a-card class="mb20">
            <titleName title="危险作业管理模板设置"></titleName>
            <a-form-model
                :model="formData"
                :labelCol="{ lg: { span: 6 }, sm: { span: 6 } }"
                :wrapperCol="{ lg: { span: 16 }, sm: { span: 16 } }"
            >
                <a-row :gutter="24">
                    <a-col :md="8" :sm="8">
                        <a-form-model-item label="危险作业类别">
                            <a-select disabled placeholder="请选择" v-model="id">
                                <a-spin v-if="fetchingList" slot="notFoundContent" size="small" />
                                <a-select-option v-for="i of selectList" :value="i.id" :key="i.id">{{
                                    i.name
                                }}</a-select-option>
                            </a-select>
                        </a-form-model-item>
                    </a-col>
                </a-row>
                <a-row :gutter="24">
                    <a-col :md="24" :sm="24">
                        <div class="flex-row mb20">
                            <h3>基础信息字段设置</h3>
                            <a-button :disabled="id == ''" class="ml20" type="primary" @click="addLine()"
                                >添加行</a-button
                            >
                        </div>
                        <s-table
                            bordered
                            ref="table"
                            size="default"
                            rowKey="id"
                            :columns="columns"
                            :data="loadData"
                            :isDelete="true"
                            :alert="true"
                            show-size-changer
                            show-quick-jumper
                            :showPagination="false"
                        >
                            <template slot="name" slot-scope="text, record">
                                <BaseInput
                                    v-if="record.editable"
                                    :value="text"
                                    placeholder="请输入"
                                    @change="(e) => handleChange(e.target.value, record.key, 'name')"
                                ></BaseInput>
                                <span v-else>{{ text }}</span>
                            </template>
                            <template slot="chooseInput" slot-scope="text, record">
                                <BaseInput
                                    v-if="record.editable && (record.type == 4 || record.type == 3)"
                                    :value="text"
                                    :maxLength="100"
                                    placeholder="请输入"
                                    @change="(e) => handleChange(e.target.value, record.key, 'chooseInput')"
                                ></BaseInput>
                                <span v-else>{{ text }} </span>
                            </template>

                            <template slot="type" slot-scope="text, record">
                                <a-select
                                    :disabled="!record.editable"
                                    placeholder="请选择类型"
                                    @change="handleChangeSelect(record)"
                                    v-model="record.type"
                                >
                                    <a-select-option v-for="i in types" :value="i.value" :key="i.value">{{
                                        i.label
                                    }}</a-select-option>
                                </a-select>
                            </template>
                            <template slot="action" slot-scope="text, record, index">
                                <span v-if="record.editable">
                                    <a @click="() => save(record)">保存</a>
                                    <a-divider type="vertical" />
                                    <a-popconfirm title="确定要取消保存?" @confirm="() => cancel(record.key, index)">
                                        <a>取消</a>
                                    </a-popconfirm>
                                </span>
                                <span v-else>
                                    <a :disabled="editingKey !== ''" @click="() => edit(record.key)">编辑</a>
                                    <a-divider type="vertical" />
                                    <a-popconfirm title="确定要删除?" @confirm="() => del(record, index)">
                                        <a>删除</a>
                                    </a-popconfirm>
                                </span>
                            </template>
                        </s-table>
                    </a-col>
                    <!-- </a-row>
                <a-row :gutter="24"> -->
                    <a-col :md="24" :sm="24" class="mt20">
                        <div class="flex-row mb20">
                            <h3>主要安全措施</h3>
                            <a-button :disabled="id == ''" class="ml20" type="primary" @click="addLine1()"
                                >添加行</a-button
                            >
                        </div>
                        <s-table
                            bordered
                            ref="table1"
                            size="default"
                            rowKey="id"
                            :columns="columns1"
                            :data="loadData1"
                            :isDelete="true"
                            :alert="true"
                            show-size-changer
                            show-quick-jumper
                            :showPagination="false"
                        >
                            <template slot="name" slot-scope="text, record">
                                <BaseInput
                                    v-if="record.editable"
                                    :value="text"
                                    :maxLength="100"
                                    placeholder="请输入"
                                    @change="(e) => handleChange1(e.target.value, record.key, 'name')"
                                ></BaseInput>
                                <span v-else>{{ text }}</span>
                            </template>

                            <template slot="type" slot-scope="text, record">
                                <a-select :disabled="!record.editable" placeholder="请选择类型" v-model="record.type">
                                    <a-select-option :value="1">是</a-select-option>
                                    <a-select-option :value="0">否</a-select-option>
                                </a-select>
                            </template>
                            <template slot="action" slot-scope="text, record, index">
                                <span v-if="record.editable">
                                    <a @click="() => save1(record)">保存</a>
                                    <a-divider type="vertical" />
                                    <a-popconfirm title="确定要取消保存?" @confirm="() => cancel1(record.key, index)">
                                        <a>取消</a>
                                    </a-popconfirm>
                                </span>
                                <span v-else>
                                    <a :disabled="editingKey !== ''" @click="() => edit1(record.key)">编辑</a>
                                    <a-divider type="vertical" />
                                    <a-popconfirm title="确定要删除?" @confirm="() => del1(record, index)">
                                        <a>删除</a>
                                    </a-popconfirm>
                                </span>
                            </template>
                        </s-table>
                    </a-col>
                </a-row>
            </a-form-model>
        </a-card>

        <div class="tool-btns page-btn-right-top">
            <a-button type="primary" @click="handleClose">关闭</a-button>
        </div>
    </base-breadcrumb>
</template>
<script>
import { STable } from '@/components'

import {
    getDangerWork,
    addDangerWork,
    updateDangerWork,
    deleteDangerWork,
    addDangerWorkMajor,
    updateDangerWorkMajor,
    deleteDangerWorkMajor,
} from '@/api/safetySupervision/dangerousOperations'
import { getSelectListByType } from '@/api/safetySupervision/common.js'
const columns = [
    {
        title: '名称',
        dataIndex: 'name',
        scopedSlots: { customRender: 'name' },
        width: '30%',
    },
    {
        title: '数据类型选择',
        dataIndex: 'type',
        scopedSlots: { customRender: 'type' },
        width: '25%',
    },

    {
        title: '选项值（、号隔开）',
        dataIndex: 'chooseInput',
        scopedSlots: { customRender: 'chooseInput' },
        width: '30%',
    },
    {
        title: '操作',
        dataIndex: 'action',
        scopedSlots: { customRender: 'action' },
    },
]
const columns1 = [
    {
        title: '名称',
        dataIndex: 'name',
        scopedSlots: { customRender: 'name' },
        width: '45%',
    },
    {
        title: '数据选项值',
        dataIndex: 'type',
        scopedSlots: { customRender: 'type' },
        width: '40%',
    },

    {
        title: '操作',
        dataIndex: 'action',
        scopedSlots: { customRender: 'action' },
    },
]
export default {
    name:'a'+Date.now(),    components: {
        STable,
    },
    data() {
        this.columns = columns
        this.columns1 = columns1

        return {
            editingKey: '',
            editingKey1: '',
            id: '',
            formData: { basicInformationList: [], majorSecurityList: [] },

            queryParam: {
                type: 21,
            },
            types: [
                {
                    label: '单行文本',
                    value: 0,
                },
                {
                    label: '多行文本',
                    value: 1,
                },
                {
                    label: '数字输入',
                    value: 2,
                },
                {
                    label: '单选',
                    value: 3,
                },
                {
                    label: '多选',
                    value: 4,
                },
                {
                    label: '日期',
                    value: 5,
                },
                {
                    label: '作业工人',
                    value: 6,
                },
                {
                    label: '管理人员',
                    value: 7,
                },
                {
                    label: '施工区域选择',
                    value: 8,
                },
                {
                    label: '气体检测',
                    value: 9,
                },
                {
                    label: '个人防护器材',
                    value: 10,
                },
            ],

            fetchingList: false,
            selectList: [],
            tableList: [],
            loadData: () => {
                if (this.formData.basicInformationList?.length) {
                    return new Promise((resolve, reject) => {
                        resolve({
                            data: this.formData.basicInformationList,
                        })
                    })
                }
            },
            loadData1: () => {
                if (this.formData.majorSecurityList?.length) {
                    return new Promise((resolve, reject) => {
                        resolve({
                            data: this.formData.majorSecurityList,
                        })
                    })
                }
            },
        }
    },

    created() {
        this.id = this.$route.query.id

        this.getSelectListByTypeReq()
    },

    watch: {
        id: {
            immediate: true,
            handler(val) {
                if (val) {
                    this.$nextTick(() => {
                        this.getData()
                    })
                }
            },
        },
    },
    methods: {
        async getSelectListByTypeReq() {
            this.fetchingList = true
            const [err, res] = await getSelectListByType(this.queryParam)
            this.fetchingList = false
            if (!err) {
                this.selectList = res.data
            }
        },
        async getData() {
            this.$refs.table.localLoading = true
            this.$refs.table1.localLoading = true
            const [err, res] = await getDangerWork({ id: this.id })
            this.$refs.table.localLoading = false
            this.$refs.table1.localLoading = false
            if (!err) {
                this.formData = res.data
                this.formData.basicInformationList.forEach((item, index) => {
                    item.editable = false
                    item.key = index
                    if (item.type != 4 && item.type != 3) {
                        item.chooseInput = '-'
                    }
                })
                this.formData.majorSecurityList.forEach((item, index) => {
                    item.editable = false
                    item.key = index
                })
                console.log(this.formData)
                this.$refs.table.refresh(true)
                this.$refs.table1.refresh(true)
            }
        },
        addLine() {
            this.formData.basicInformationList.push({
                key: this.formData.basicInformationList.length + 1,
                name: '',
                editable: true,
                type: 0,
            })
            console.log(this.formData.basicInformationList)
            this.cacheData = this.formData.basicInformationList.map((item) => ({ ...item }))
            this.$refs.table.refresh(true)
        },
        addLine1() {
            this.formData.majorSecurityList.push({
                key: this.formData.majorSecurityList.length + 1,
                name: '',
                editable: true,
                type: 1,
            })
            console.log(this.formData.majorSecurityList)
            this.cacheData1 = this.formData.majorSecurityList.map((item) => ({ ...item }))
            this.$refs.table1.refresh(true)
        },
        async del(data, idx) {
            this.$refs.table.localLoading = true

            const [err, res] = await deleteDangerWork({ id: data.id, basicId: this.formData.id })
            this.$refs.table.localLoading = false
            if (!err) {
                this.formData.basicInformationList.splice(idx, 1)
                this.$refs.table.refresh(true)
            }
        },

        async del1(data, idx) {
            this.$refs.table1.localLoading = true

            const [err, res] = await deleteDangerWorkMajor({ id: data.id, basicId: this.formData.id })
            this.$refs.table1.localLoading = false
            if (!err) {
                this.formData.majorSecurityList.splice(idx, 1)
                this.$refs.table1.refresh(true)
            }
        },

        handleChange(value, key, column) {
            const newData = [...this.formData.basicInformationList]
            const target = newData.filter((item) => key === item.key)[0]
            if (target) {
                target[column] = value
                this.formData.basicInformationList = newData
            }
        },
        handleChangeSelect(data) {
            if (data.type == 4 || data.type == 3) {
                data.chooseInput = ''
            } else {
                data.chooseInput = '-'
            }
        },
        handleChange1(value, key, column) {
            const newData = [...this.formData.majorSecurityList]
            const target = newData.filter((item) => key === item.key)[0]
            if (target) {
                target[column] = value
                this.formData.majorSecurityList = newData
            }
        },
        edit1(key) {
            const newData = [...this.formData.majorSecurityList]
            const target = newData.filter((item) => key === item.key)[0]
            this.editingKey1 = key
            if (target) {
                target.editable = true
                this.formData.majorSecurityList = newData
            }
            this.cacheData1 = this.formData.majorSecurityList.map((item) => ({ ...item }))
            this.$refs.table1.refresh(true)
        },
        edit(key) {
            const newData = [...this.formData.basicInformationList]
            const target = newData.filter((item) => key === item.key)[0]
            this.editingKey1 = key
            if (target) {
                target.editable = true
                this.formData.basicInformationList = newData
            }
            this.cacheData = this.formData.basicInformationList.map((item) => ({ ...item }))
            this.$refs.table.refresh(true)
        },
        async save1(data) {
            if (data.name == '') {
                this.$message.warning('请输入名称')
                return
            }
            const params = { ...data, basicId: this.formData.id }
            this.$refs.table1.localLoading = true
            console.log(params)
            if (data.id) {
                const [err, res] = await updateDangerWorkMajor(params)
                this.$refs.table1.localLoading = false
                data.editable = false
            } else {
                const [err, res] = await addDangerWorkMajor(params)
                this.$refs.table1.localLoading = false
                data.editable = false
                data.id = res.data.message
            }

            this.editingKey1 = ''
        },
        async save(data) {
            if (data.name == '') {
                this.$message.warning('请输入名称')
                return
            }
            const params = { ...data, basicId: this.formData.id }
            this.$refs.table.localLoading = true
            console.log(data)
            if (data.id) {
                const [err, res] = await updateDangerWork(params)
                this.$refs.table.localLoading = false
                data.editable = false
            } else {
                const [err, res] = await addDangerWork(params)
                this.$refs.table.localLoading = false
                data.editable = false
                data.id = res.data.message
            }

            this.editingKey = ''
        },
        cancel(key, index) {
            const newData = [...this.formData.basicInformationList]
            const target = newData.filter((item) => key === item.key)[0]
            this.editingKey = ''
            if (target.id) {
                if (target) {
                    Object.assign(target, this.cacheData.filter((item) => key === item.key)[0])
                    delete target.editable
                    this.formData.basicInformationList = newData
                }
            } else {
                this.formData.basicInformationList.splice(index, 1)
            }

            this.$refs.table.refresh(true)
        },
        cancel1(key, index) {
            const newData = [...this.formData.majorSecurityList]
            const target = newData.filter((item) => key === item.key)[0]
            this.editingKey1 = ''
            if (target.id) {
                if (target) {
                    Object.assign(target, this.cacheData1.filter((item) => key === item.key)[0])
                    delete target.editable
                    this.formData.majorSecurityList = newData
                }
            } else {
                this.formData.majorSecurityList.splice(index, 1)
            }

            this.$refs.table1.refresh(true)
        },
        handleClose() {
            this.$multiTab.close(this.$route.fullpath)
        },
    },
}
</script>
<style lang="less">
.flex-row {
    display: flex;
    flex-direction: row;
    justify-content: space-between;
    align-items: center;
}
</style>
